import { useEffect, useState } from 'react';
import { useAppStore } from './stores/appStore';
import { safeTauriInvoke } from './utils/tauriHelper';
import MainPage from './pages/MainPage';
import SettingsPage from './pages/SettingsPage';
import DisguisePage from './pages/DisguisePage';
import GlobalShortcuts from './components/GlobalShortcuts';
import { WindowInfo } from './types';


function App() {
  const { 
    currentMode, 
    opacity, 
    alwaysOnTop, 
    isVisible,
    setWindowInfo,
    shortcuts
  } = useAppStore();

  // 检查是否在Tauri环境中运行
  const [isTauriEnv, setIsTauriEnv] = useState<boolean | null>(null);
  
  // 初始化环境检测
  useEffect(() => {
    const checkTauriEnvironment = () => {
      console.log('🔍 检查运行环境...');
      
      // 检查是否在Tauri环境中
      const hasWindow = typeof window !== 'undefined';
      const hasTauri = hasWindow && window.__TAURI__ !== undefined;
      const hasTauriIPC = hasWindow && window.__TAURI_IPC__ !== undefined;
      const hasTauriInvoke = hasWindow && window.__TAURI__ && (window.__TAURI__ as any).invoke !== undefined;
      
      const isInTauri = hasTauri && hasTauriIPC && hasTauriInvoke;
      
      console.log('🔍 环境检测结果:', {
        hasWindow,
        hasTauri,
        hasTauriIPC,
        hasTauriInvoke,
        isInTauri,
        currentURL: hasWindow ? window.location.href : 'unknown'
      });
      
      setIsTauriEnv(isInTauri);
      
      if (isInTauri) {
        console.log('✅ 检测到Tauri环境，开始初始化窗口...');
        initializeWindow();
      } else {
        console.warn('⚠️ 检测到浏览器环境，请在Tauri应用中运行');
      }
    };
    
    const initializeWindow = async () => {
      try {
        console.log('🔧 步骤1: 设置初始透明度...');
        await safeTauriInvoke('set_window_opacity', { opacity });
        console.log('✅ 透明度设置成功');
        
        console.log('🔧 步骤2: 设置置顶状态...');
        await safeTauriInvoke('set_always_on_top', { alwaysOnTop });
        console.log('✅ 置顶状态设置成功');
        
        console.log('🔧 步骤3: 获取窗口信息...');
        const windowInfo = await safeTauriInvoke('get_window_info');
        setWindowInfo(windowInfo as WindowInfo);
        console.log('✅ 窗口信息获取成功:', windowInfo);
        
        console.log('🎉 窗口初始化完成');
      } catch (error) {
        console.error('❌ 窗口初始化失败:', error);
      }
    };

    // 延迟检测，确保DOM完全加载
    const timer = setTimeout(checkTauriEnvironment, 100);
    
    return () => clearTimeout(timer);
  }, []);

  // 监听透明度变化（仅在Tauri环境中）
  useEffect(() => {
    if (!isTauriEnv) return;
    
    const updateOpacity = async () => {
      try {
        await safeTauriInvoke('set_window_opacity', { opacity });
      } catch (error) {
        console.error('设置透明度失败:', error);
      }
    };

    updateOpacity();
  }, [opacity, isTauriEnv]);

  // 监听置顶状态变化（仅在Tauri环境中）
  useEffect(() => {
    if (!isTauriEnv) return;
    
    const updateAlwaysOnTop = async () => {
      try {
        await safeTauriInvoke('set_always_on_top', { alwaysOnTop });
      } catch (error) {
        console.error('设置置顶状态失败:', error);
      }
    };

    updateAlwaysOnTop();
  }, [alwaysOnTop, isTauriEnv]);

  // 监听可见性变化（仅在Tauri环境中）
  useEffect(() => {
    if (!isTauriEnv) return;
    
    const updateVisibility = async () => {
      try {
        await safeTauriInvoke('toggle_window_visibility', { visible: isVisible });
      } catch (error) {
        console.error('设置窗口可见性失败:', error);
      }
    };

    updateVisibility();
  }, [isVisible, isTauriEnv]);

  // 注册全局快捷键（仅在Tauri环境中）
  useEffect(() => {
    if (!isTauriEnv) return;
    
    const registerShortcuts = async () => {
      try {
        // 这里需要在Tauri后端实现全局快捷键注册
        console.log('注册全局快捷键:', shortcuts);
      } catch (error) {
        console.error('注册全局快捷键失败:', error);
      }
    };

    registerShortcuts();
  }, [shortcuts, isTauriEnv]);

  // 根据当前模式渲染不同的页面
  const renderCurrentPage = () => {
    switch (currentMode) {
      case 'reading':
        return <MainPage />;
      case 'settings':
        return <SettingsPage />;
      case 'disguise':
        return <DisguisePage />;
      default:
        return <MainPage />;
    }
  };

  // 如果环境检测还在进行中，显示加载状态
  if (isTauriEnv === null) {
    return (
      <div className="h-screen w-screen bg-gray-900 text-white flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
          <p className="text-lg">正在检测运行环境...</p>
        </div>
      </div>
    );
  }

  // 如果不在Tauri环境中，显示提示页面
  if (!isTauriEnv) {
    return (
      <div className="h-screen w-screen bg-gradient-to-br from-blue-900 to-purple-900 text-white flex items-center justify-center">
        <div className="max-w-md mx-auto text-center p-8 bg-black/20 rounded-lg backdrop-blur-sm">
          <div className="text-6xl mb-6">🚀</div>
          <h1 className="text-2xl font-bold mb-4">微信读书摸鱼工具</h1>
          <div className="bg-yellow-500/20 border border-yellow-500/50 rounded-lg p-4 mb-6">
            <p className="text-yellow-200 mb-2">⚠️ 检测到您正在浏览器中运行</p>
            <p className="text-sm text-gray-300">
              此应用需要在 Tauri 桌面环境中运行才能正常工作
            </p>
          </div>
          <div className="text-left space-y-3 text-sm text-gray-300">
            <p><strong>请按以下步骤启动应用：</strong></p>
            <ol className="list-decimal list-inside space-y-1 ml-4">
              <li>关闭此浏览器页面</li>
              <li>在项目根目录运行：<code className="bg-gray-800 px-2 py-1 rounded">pnpm tauri dev</code></li>
              <li>等待 Tauri 桌面应用窗口打开</li>
            </ol>
          </div>
          <div className="mt-6 text-xs text-gray-400">
            当前URL: {window.location.href}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="app-container w-full h-screen overflow-hidden">
      <GlobalShortcuts 
        shortcuts={{
          toggleVisibility: 'Ctrl+Shift+H',
          increaseOpacity: 'Ctrl+Shift+Up',
          decreaseOpacity: 'Ctrl+Shift+Down',
          toggleDisguise: 'Ctrl+Shift+D'
        }}
      />
      {renderCurrentPage()}
    </div>
  );
}

export default App;